package com.lepu.app.usercenter;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.app.application.MyApplication;
import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.MyDialog;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.usercenter.util.UserCenterUtil;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewRightButtonListener;
import com.lepu.pasm.R;

public class LoginActivity extends BaseFragmentActivity implements
		AsyncRequest, OnEditorActionListener,OnTopbarNewLeftLayoutListener,OnTopbarNewRightButtonListener {

	private static final String REQUEST_LOGIN = "request_login";

	private static final int MSG_LOGIN_SUCCESS = 10;
	private static final int MSG_LOGIN_FAIL = 11;
	
	private boolean mFirstEnter = false;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {

		mNeedSwipeBack = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.usercenter_login_activity);

		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		
		if(mFirstEnter)
		{
			finishAnim(0,0);
		}else{
			finishAnim(R.anim.lib_push_down_up_in, R.anim.lib_push_down_up_out);
		}
		
	}
	
	@Override
	public void onTopbarLeftLayoutSelected() {
		finishAnim(R.anim.lib_push_down_up_in,
				R.anim.lib_push_down_up_out);
	}
	
	@Override
	public void onTopbarRightButtonSelected() {
		finish();
		
		LoginUtil.jumpMainActivity(this);
	}

	/**
	 * 初始化方法
	 */
	private void init() {

		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("登录");
		topbar.setonTopbarNewLeftLayoutListener(this);
		
		Bundle data = getIntent().getExtras();
		if(data != null && data.size() > 0)
		{
			mFirstEnter = data.getBoolean("first_enter", false);
		}
		
		if(mFirstEnter)
		{
			topbar.setTopbarLeftLayoutHide();
			topbar.setRightText("跳过");
			topbar.setOnTopbarNewRightButtonListener(this);
		}else{
			topbar.setTopbarLeftLayout(R.drawable.app_icon_close,0,0);
		}
		

		Button loginButton = (Button) findViewById(R.id.loginButton);
		TextView registerTextView = (TextView) findViewById(R.id.registerTextView);
		TextView forgetPwdTextView = (TextView) findViewById(R.id.forgetPwdTextView);

		loginButton.setOnClickListener(mOnClickListener);
		registerTextView.setOnClickListener(mOnClickListener);
		forgetPwdTextView.setOnClickListener(mOnClickListener);

		LinearLayout contentLayout = (LinearLayout) findViewById(R.id.contentLayout);
		contentLayout.setOnTouchListener(new View.OnTouchListener() {

			@SuppressLint("ClickableViewAccessibility")
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				UtilityBase.closeSoftInput(LoginActivity.this);
				return false;
			}
		});

		EditText pwdEditText = (EditText) findViewById(R.id.pwdEditText);
		pwdEditText.setOnEditorActionListener(this);
	}
	
	private void login() {
		EditText userEditText = (EditText) findViewById(R.id.userEditText);
		EditText pwdEditText = (EditText) findViewById(R.id.pwdEditText);

		String userContent = userEditText.getText().toString().trim();
		String pwdContent = pwdEditText.getText().toString().trim();

		boolean flag = UserCenterUtil.login(this, this, REQUEST_LOGIN,
				userContent, pwdContent);
		if (flag) {
			showProgressDialog();
		}
	}
	
	private void checkIfFinishInfo(String loginDataString)
	{
		LoginInfo loginInfo = LoginInfo.parseLoginInfo(loginDataString);
		
		if(LoginUtil.checkNeedFinishInfo(loginInfo))
		{
			MyApplication.getInstance().mTempLoginInfo = loginInfo;
			
			String message = "您还没有完善信息，请您先完善信息！";
			MyDialog dialog = new MyDialog(this)
					.setMessage(message)
					//.setNegativeButtonSplitImageHide(true)
					.setPositiveButton(R.string.app_ok,
							new View.OnClickListener() {

								@Override
								public void onClick(View v) {
									
									finishAnim(R.anim.lib_push_down_up_in,
											R.anim.lib_push_down_up_out);
									
									LoginUtil.jumpUserInfoActivity(LoginActivity.this);
								}
							});

			dialog.create(null);
			dialog.setCancelable(false);
			dialog.setCanceledOnTouchOutside(false);
			dialog.showMyDialog();
			
		}else{
			//切换登录，删除缓存头像
			LoginUtil.clearUserIcon(this);
			
			LoginInfo.saveLoginInfo(this, loginInfo);
			
			finishAnim(R.anim.lib_push_down_up_in,
					R.anim.lib_push_down_up_out);
			// 登录成功更新
			ObserverManager.getInstance().notify(
					ObserverConst.NOTIFY_MY_LOGIN_STATE_CHANGE, null,
					LoginInfo.TYPE_LOGIN);
			LoginUtil.jumpMainActivity(LoginActivity.this);
		}
	}

	View.OnClickListener mOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {

			Intent intent = null;

			switch (v.getId()) {
			case R.id.loginButton:
				login();

				break;
			case R.id.registerTextView:

				intent = new Intent(LoginActivity.this, RegisterActivity.class);
				startActivityAnim(intent, R.anim.lib_push_down_up_in,
						R.anim.lib_push_down_up_out);
				break;
			case R.id.forgetPwdTextView:

				intent = new Intent(LoginActivity.this, ForgetPwdActivity.class);
				startActivity(intent, true);
				break;

			default:
				break;
			}
		}
	};

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_LOGIN_SUCCESS:

				hideProgressDialog();

				String data = (String) msg.obj;
				checkIfFinishInfo(data);

				break;
			case MSG_LOGIN_FAIL:

				hideProgressDialog();
				break;

			default:
				break;
			}
		};
	};

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_LOGIN)) {

			String result = (String) data;
			JSONObject dataObject = null;
			try {
				JSONObject jsonObject = new JSONObject(result);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				dataObject = (JSONObject) obj1.get("DetailInfo");
				
				String dataString = dataObject
						.toString();
				Message msg = mHandler.obtainMessage();
				msg.what = MSG_LOGIN_SUCCESS;
				msg.obj = dataString;
				mHandler.sendMessage(msg);
				
			} catch (JSONException e) {
				e.printStackTrace();
				mHandler.sendEmptyMessage(MSG_LOGIN_FAIL);
			}
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_LOGIN)) {
			mHandler.sendEmptyMessage(MSG_LOGIN_FAIL);
		}
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		switch (actionId) {
		case EditorInfo.IME_ACTION_DONE:

			login();
			break;
		}
		return true;
	}
	
}
